/**
 *
 */
package com.javademos.train.dynamicdatasource.datasources;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 踩坑填坑
 * @Description: [ 多数据源配置 ]
 * @Email: 120987555@qq.com
 * @Date: 2017年9月14日 下午2:24:31
 * @Version: V1.0
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean(name = "test")
    @ConfigurationProperties("spring.datasource.druid.first")
    public DataSource firstDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "ye")
    @ConfigurationProperties("spring.datasource.druid.second")
    public DataSource secondDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean
    public DynamicDataSource dataSource() {
        Map<String, DataSource> targetDataSources = new HashMap<String, DataSource>();
        targetDataSources.put(DataSourceNames.FIRST, firstDataSource());
        targetDataSources.put(DataSourceNames.SECOND, secondDataSource());

        return new DynamicDataSource(firstDataSource(), targetDataSources);
    }
}